<template>
  <div class="add-list-wrapper">
    <div class="add-item">背景</div>
    <div class="add-item">素材</div>
    <div class="add-item" @click="onSelectText">文字</div>
    <div class="add-item" @click="onSelectImage">图片</div>
    <van-dialog
      v-model="inputTextVisible"
      title="设置文字"
      @confirm="onTextConfirm"
      show-cancel-button
    >
      <div class="form-wrapper">
        <textarea v-model="text" class="form-textarea"></textarea>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import { Dialog } from 'vant'
import { addText, addImage } from './store'
export default {
  components: {
    [Dialog.Component.name]: Dialog.Component
  },
  data () {
    return {
      inputTextVisible: false,
      text: ''
    }
  },
  methods: {
    showTextWrapper (text) {
      this.inputTextVisible = true
      this.text = text
    },
    onTextConfirm () {
      this.$emit('on-text', this.text)
      addText(this.text)
      this.$emit('close')
      this.text = ''
    },
    onSelectText () {
      this.inputTextVisible = true
    },
    onSelectImage () {
      const input = document.createElement('input')
      input.setAttribute('type', 'file')
      input.addEventListener('change', (e) => {
        const file = e.target.files[0]
        const url = URL.createObjectURL(file)
        addImage(url)
        this.$emit('close')
        document.body.removeChild(input)
      })
      input.style.display = 'none'
      document.body.appendChild(input)
      input.click()
    }
  }
}
</script>

<style lang="stylus" scoped>
.form-wrapper {
  padding: 6px 10px;

  .form-textarea {
    width: 100%;
    height: 100px;
    border: 1px solid #f2f2f2;
    border-radius: 4px;
    padding: 10px;
    box-sizing border-box;
    box-shadow: none
  }
}

.add-list-wrapper {
  display: flex;
  flex-direction: column;
  padding: 10px 15px;

  .add-item {
    padding: 10px 0;
    text-align: center;
    border-bottom: 1px solid #f1f1f1;

    &:last-child {
      border-bottom: none;
    }
  }
}
</style>
